package com.javaweb.system.config

import com.javaweb.pojo.SysUser
import com.javaweb.service.SysUserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Component
import java.util.*


/**
 * 用户登录判断
 * @author Siaze
 * @date 2021/12/10
 */
@Component
class UserDetailsServiceImpl: UserDetailsService {

    /**
     * sysUserService是sys_user表（用户表）查询工具，可以通过自定义查询条件查询数据
     */
    @Autowired
    lateinit var sysUserService: SysUserService

    /**
     * @param username 通过userName（账号）查询并返回UserDetails比较密码是否相同
     */
    override fun loadUserByUsername(username: String?): UserDetails {
        /*
            查询用户
         */
        val user: SysUser = sysUserService.getById(username) ?: throw UsernameNotFoundException("用户不存在")
        /*
            设置权限
         */
        val authorities: MutableList<GrantedAuthority> = ArrayList<GrantedAuthority>()
        authorities.add(SimpleGrantedAuthority(user.roles))
        /*
            返回UserDetails
         */
        return User(user.userId.toString(), BCryptPasswordEncoder().encode(user.password), authorities)
    }
}